package com.ruoyi.web.controller.common;

import cn.xuyanwu.spring.file.storage.FileInfo;
import cn.xuyanwu.spring.file.storage.FileStorageService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.SysAttach;
import com.ruoyi.system.service.ISysAttachService;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 素材附件Controller
 * 
 * @author ruoyi
 * @date 2023-04-10
 */
@RestController
@RequestMapping("/system/attach")
public class SysAttachController extends BaseController
{
    @Resource
    private ISysAttachService sysAttachService;

    @Resource
    private FileStorageService fileStorageService;

    /**
     * 查询素材附件列表
     */
    @GetMapping("/list")
    public TableDataInfo list(SysAttach sysAttach)
    {
        startPage();
        List<SysAttach> list = sysAttachService.selectSysAttachList(sysAttach);
        return getDataTable(list);
    }

    @RequestMapping("/upload")
    public Map<String,String> upload(MultipartFile file){

        if (file == null) {
            return new HashMap<>(1);
        }
        FileInfo fileInfo = fileStorageService.of(file).upload();
        Map<String,String> map = new HashMap<>();
        map.put("state","SUCCESS");
        map.put("url",fileInfo.getUrl());
        return map;
    }

    /**
     * 导出素材附件列表
     */
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysAttach sysAttach)
    {
        List<SysAttach> list = sysAttachService.selectSysAttachList(sysAttach);
        ExcelUtil<SysAttach> util = new ExcelUtil<SysAttach>(SysAttach.class);
        util.exportExcel(response, list, "素材附件数据");
    }

    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(sysAttachService.selectSysAttachById(id));
    }

    /**
     * 新增素材附件
     */
    @PostMapping
    public AjaxResult add(@RequestBody SysAttach sysAttach)
    {
        return toAjax(sysAttachService.insertSysAttach(sysAttach));
    }

    /**
     * 修改素材附件
     */
    @PutMapping
    public AjaxResult edit(@RequestBody SysAttach sysAttach)
    {
        return toAjax(sysAttachService.updateSysAttach(sysAttach));
    }

    /**
     * 删除素材附件
     */
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(sysAttachService.deleteSysAttachByIds(ids));
    }
}
